/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ObjectsManager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author fabualves
 */
public class StreamObject {

    private HashMap<Integer, byte[]> chunks;
    private String filename;
    private int totalOfChunks;
    private String providerIP;
    private int port;
    private File directory;

    public StreamObject(String providerIP, int port, String filename, int totalOfChunks) {
        this.providerIP = providerIP;
        this.port = port;
        this.filename = filename;
        this.totalOfChunks = totalOfChunks;
        this.chunks = new HashMap<Integer, byte[]>(totalOfChunks);
        this.directory = new File(providerIP+"_"+port);
        this.cleanDirectory();
    }

    public boolean addChunk(byte[] chunk, int order) {
        if (chunks != null && chunks.get(order) == null) {
            chunks.put(order, chunk);
            return true;
        } else {
            return false;
        }
    }

    public boolean isComplete() {
        if((chunks != null)&&(chunks.size() == this.totalOfChunks)){
            return true;
        }
        return false;
    }

    public boolean saveFile() {
        
        if (this.chunks != null && this.chunks.size() > 0 && this.isComplete()) {
            try {
                File file = new File(directory.getAbsolutePath() + "/" + this.filename);
                if(file.exists()){
                    file.delete();
                }
                FileOutputStream fileWriter = new FileOutputStream(file, true);
                System.out.println(directory.getAbsolutePath() + "/" + this.filename);
                for(int i =1; i<=this.totalOfChunks; i++){
                    fileWriter.write(this.chunks.get(i));
                }
                this.chunks = null;
                fileWriter.close();
                return true;
            } catch (FileNotFoundException ex) {
                Logger.getLogger(StreamObject.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(StreamObject.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        return false;
    }

    public String getFilename() {
        return filename;
    }
    
    private void cleanDirectory(){
        if(!directory.exists()){
            directory.mkdir();
        }
    }
}
